package Mysql;

import Main.StartMain;
import Message.Tips;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;

/**
 * 数据库启动类
 */
public class Start {

    private static Connection connection = null;//数据库连接
    private static String Url , Username , Password , Port , Table;//数据库信息

    /**
     * 初始化检查数据库
     */
    public static boolean Mysql_Start(){
        Date startDate = new Date();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            Tips.Error(e.getMessage(),false);
            return false;
        }
        Map<String , Object> config = StartMain.getConfigData("mysql");//获取配置信息
        Url = (String) config.get("mysql_url");
        Username = (String) config.get("mysql_username");
        Password = (String) config.get("mysql_password");
        Port = (String) config.get("mysql_port");
        Table = (String) config.get("mysql_table");
        //获取配置信息
        if (!setConnection()) return false;//连接数据库
        if (!Update.initCreateTable()) return false;//数据库初始化失败
        Date endDate = new Date();
        long span = endDate.getTime() - startDate.getTime();
        Tips.Info("本次MYSQL复位连接延时 " + span + " 毫秒");
        return true;
    }

    /**
     * 重新连接
     */
    public static boolean reConnection(){
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
                Tips.Error(e.getMessage());
            }
        }
        //关闭连接数据库
        if (!setConnection()) return false;
        Tips.Info("数据库重新连接成功!");
        return true;
    }

    /**
     * 连接数据库
     */
    public static boolean setConnection(){
        try {
            connection = DriverManager.getConnection(
                    "jdbc:mysql://" + Url + ":" + Port + "/" + Table,
                    Username, Password);
        } catch (SQLException e) {
            e.printStackTrace();
            Tips.Error(e.getMessage() , false);
            return false;
        }
        return true;
    }

    /**
     * 断开数据库连接
     */
    public static void disConnection(){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
            Tips.Warm(e.getMessage());
        }
        connection = null;
        Tips.Info("数据库已断开连接...");
    }

    public static Connection getConnection() {
        return connection;
    }
}
